package com.zxl.live.screen.screen.ui.widget.anim;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * Created by Administrator on 2018/1/24.
 */
public abstract class BaseAnimationView extends SurfaceView implements SurfaceHolder.Callback, Runnable {

    private boolean mIsRunning;

    protected int mGapTime = 60;

    protected int mCurrentIndex;

    private ZipDataHelper mZipDataHelper;

    private OnFrameFinishedListener mOnFrameFinishedListener;

    public BaseAnimationView(Context context, AttributeSet attrs) {
        super(context, attrs);
        getHolder().addCallback(this);
        setZOrderMediaOverlay(true);
        getHolder().setFormat(PixelFormat.TRANSLUCENT);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        stop();
    }

    @Override
    public void run() {
        if (mOnFrameFinishedListener != null) {
            mOnFrameFinishedListener.onStart();
        }
        if (null != mZipDataHelper) {
            mZipDataHelper.init();
        }
        while (mIsRunning) {
            try {
                drawView();
                Thread.sleep(mGapTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (mOnFrameFinishedListener != null) {
            mOnFrameFinishedListener.onStop();
        }
    }

    protected abstract void drawView();

    public void setOnFrameFinishedListener(OnFrameFinishedListener mOnFrameFinishedListener) {
        this.mOnFrameFinishedListener = mOnFrameFinishedListener;
    }

    public void setData(String path) {
        mZipDataHelper = new ZipDataHelper(path);
    }

    public Bitmap getCurrentBitmap() {
        return mZipDataHelper == null ? null : mZipDataHelper.createBitmap(mCurrentIndex);
    }

    public int dataSize() {
        return mZipDataHelper == null ? 0 : mZipDataHelper.size();
    }

    public void setGapTime(int mGapTime) {
        this.mGapTime = mGapTime;
    }

    public void start() {
        if (!mIsRunning) {
            mIsRunning = true;
            new Thread(this).start();
        }
    }

    public void stop() {
        mIsRunning = false;
    }

    public interface OnFrameFinishedListener {

        void onStart();

        void onStop();
    }

}
